package com.soulkun.smarthome.ui.main.personal.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.lifecycle.ViewModel
import com.soulkun.smarthome.logic.repository.ApiRepository
import com.soulkun.smarthome.logic.vo.AlertMessageHistoryItemVO
import com.soulkun.smarthome.logic.vo.AlertMessageHistoryVO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import soulkun.library.mvvm.adapter.clearAndAddAll
import soulkun.library.utils.logE
import soulkun.library.utils.time.DateUtils
import soulkun.library.utils.time.TimeUtils
import java.util.Comparator

class AppMainPersonalMessageAlertViewModel : ViewModel() {

    val alertMessageList = ObservableArrayList<AlertMessageHistoryVO>()

    fun getAlertMessageList() = ApiRepository.getAlertMessageList(this) {
        val list = arrayListOf<AlertMessageHistoryVO>()
        withContext(Dispatchers.Default) {
            var date = 0L
            val sortedList = it.data.sortedBy { alertMessageDTO -> alertMessageDTO.at }.reversed() //时间降序
            sortedList.forEach(action = { alertMessageDTO ->
                val messageDate = DateUtils.stringToDate(alertMessageDTO.at).time
                if (date != messageDate) {
                    list.add(AlertMessageHistoryVO(messageDate, ObservableArrayList()))
                    date = messageDate
                }
                list.last().messageList.add(
                    AlertMessageHistoryItemVO(
                        "家庭“${alertMessageDTO.familyName}”中设备“${alertMessageDTO.deviceName}”的属性“${alertMessageDTO.attributeDescription}”${alertMessageDTO.content}",
                        TimeUtils.stringToTime(alertMessageDTO.at, "yyyy-MM-dd HH:mm:ss.SSS") ?: ""
                    )
                )
            })
        }
        withContext(Dispatchers.Main) {
            alertMessageList.clearAndAddAll(list)
        }
    }

}